package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：部门
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> queryTree() {
        List<Department> allDepts = departmentMapper.findAll();
        HashMap<Long,Department> allDeptMap = new HashMap<>();
        List<Department> deptTree = new ArrayList<>();
        for (Department dept : allDepts){
            allDeptMap.put(dept.getId(),dept);
        }
        for (Department temp :allDepts){
            if(temp.getParentId()==null){
                deptTree.add(temp);
            }else{
                Department parent = allDeptMap.get(temp.getParentId());
                if(parent!=null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return deptTree;
    }

}
